package medium.最接近的三数之和;

import java.util.Arrays;

/**
 * @author CodeX
 * @since 2021-09-29 15:39:44
 */
public class ThreeSumClosest {
    public static int threeSumClosest(int[] nums, int target) {
        int n = nums.length;
        Arrays.sort(nums);
        int result = 99999;
        for (int a = 0; a < n; a++) {
            if (a > 0 && nums[a] == nums[a - 1]) {
                continue;
            }

            int b = a + 1, c = n - 1;
            while (b < c) {
                int sum = nums[a] + nums[b] + nums[c];
                if (sum == target) {
                    return target;
                }

                if (Math.abs(sum - target) < Math.abs(result - target)) {
                    result = sum;
                }

                if (sum > target) {
                    // 如果和大于target，将c的指针向左移
                    int c1 = c - 1;
                    while (c < c1 && nums[c] == nums[c1]) {
                        c1--;
                    }
                    c = c1;
                } else {
                    // 如果和小与target，将b的指针向右移
                    int b1 = b + 1;
                    while (b1 < c && nums[b] == nums[b1]) {
                        b1++;
                    }
                    b = b1;
                }
            }
        }
        return result;
    }

    public static void main(String[] args) {
        int[] nums = {1, 3, 4, 5};
        int target = 7;
        System.out.println(threeSumClosest(nums, target));

    }
}
